// let { validatePhone } = require('../../utils/util');
// let { toast } = require('../../utils/modal');
import { commonApi } from '../../api/index';
import { toast } from "../../utils/modal"
import { validatePhone } from "../../utils/util"
Component({
  properties: {
    show: {
      type: Boolean,
      value: false,
    },
  },
  data: {
    phone: '',
    smsCode: '',
    seconds: 60,
    sendVercodeFlag: false,
    sendVercodeTxt: '发验证码',
  },
  methods: {
    async onSendCode() {
      const phone = this.data.phone
      if (!validatePhone(phone)) {
        toast('请输入正确的手机号');
        return;
      }
      if (this.data.sendVercodeFlag) {
        return;
      }
      // 调用获取验证码的接口
      const res = await commonApi.sendVerificationCode({ phone })
      this.setVerCode();
    },
    setVerCode() {
      let timer = null;
      let count = this.data.seconds - 1;
      this.setData({
        sendVercodeFlag: true,
        seconds: count,
        sendVercodeTxt: `${count}s后发送`,
      });
      timer = setInterval(() => {
        if (this.data.seconds <= 1) {
          clearInterval(timer);
          this.setData({
            sendVercodeFlag: false,
            seconds: 60,
            sendVercodeTxt: `发验证码`,
          });
        } else {
          count = this.data.seconds - 1;
          this.setData({
            seconds: count,
            sendVercodeTxt: `${count}s后发送`,
          });
        }
      }, 1000);
    },
    onClose() {
      this.setData({
        show: false,
      });
    },
    async phoneLogin() {
      const self = this
       wx.login({
        success (res) {
          if (res.code) {
            //发起网络请求
            self.miniProgramLogin(res.code)
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    },
    async miniProgramLogin(code){
      const {phone , smsCode} = this.data
      const res = await commonApi.miniProgramLogin({ 
        phone,
        verification_code: smsCode,
        code
       })
      wx.setStorageSync("token", `Bearer ${res.token}`)
      wx.setStorageSync("code", code)
      wx.setStorageSync("openid", res.openid)
      this.onClose()
      this.triggerEvent("onClick", {
        phoneNumber: phone
       });
    },
  },
});
